<?php
namespace Admin\Frontend\Controllers;

use Admin\Models\user\XhsysUser;
use Helpers\Tool;
use Helpers\Main;
use Helpers\Template;
use Helpers\User;
use Helpers\UserPower;
use Helpers\Assets;
use Admin\Models\ask\XhaskSurvey;
use Admin\Models\ask\XhaskQuestion;
use Admin\Models\ask\XhaskOption;
use Admin\Models\ask\XhaskAnswer;
use Admin\Models\school\XhschoolInfo;
use Helpers\XhException;
use Modules\School;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

class AskController extends ControllerBase
{

    private $surveyEnum = [
        'bDisable' => [0 => '是', 1 => '否'],
        'bMutable' => [0 => '否', 1 => '是'],
        'iTarget'  => [1 => '学校', 2 => '公司']
    ];
    private $questionEnum = [
        'iQueType' => [
            1 => '单选题',
            2 => '多选题',
            3 => '下拉框',
            4 => '单行文本框',
            5 => '多行文本框'
        ],
        'bRequire' => [
            1 => '是',
            0 => '否'
        ]
    ];

    /**
     * 问卷题目题模板列表页面
     *
     * create by ck 20160722
     * modify by ck 2016924 结构更改
     */
    public function indexAction()
    {
        $this->view->pick('ask/askQuestionList');
        Assets::easyUI('js/ask/askQuestionList.js');
        Main::showNavPosition();
        UserPower::checkUserPower('Ask_QuestionList') or die(Main::showMessageModal('抱歉，您没有查看此页面的权限！', 109105001));
        Template::exists('XHAsk_Question', 'both') or die(Main::showMessageModal('配置文件不存在，请先创建！', 109105002));
        $listButtonArr = array();
        if (UserPower::checkUserPower('Ask_QuestionList_Add')) {
            $listButtonArr[] = array('id' => 'bt_list_add', 'text' => '增加', 'plain' => 'true', 'icon' => 'fa-plus');
            $this->view->setVar('AddEdit', true);                               //增加，修改页面显示标识
        }
        if (UserPower::checkUserPower('Ask_QuestionList_Edit')) {
            $listButtonArr[] = array('id' => 'bt_list_del', 'text' => '删除', 'plain' => 'true', 'icon' => 'fa-trash');
            $this->view->setVar('AddEdit', true);
        }
//        if(UserPower::checkUserPower('Ask_QuestionList_CreateSurvey')){
//            $listButtonArr[] = array('id'=>'bt_list_SetServer', 'text'=>'选择服务人员', 'plain'=>'true', 'icon'=>'fa-pencil');
//        }
        $buttonToolbar = Template::createButtonToolBar($listButtonArr);
        $this->view->setVars([
            'List'  => Template::createList('List', 'XHAsk_Question',
                ['buttonToolbar' => $buttonToolbar]
            ),
            'Form'  => Template::createForm('XHAsk_Question'),
        ]);
    }

    /**
     * 获取问题列表
     *
     * create by ck 20160722
     * modify by ck 20160924    结构更改
     */
    public function getDgDataAction()
    {
        $this->view->disable();
        $parameters['conditions'] = 'bDelete = 0';
        echo Main::runModelPaginator('\\Admin\\Models\\ask\\XhaskQuestion', $parameters);
    }

    /**
     * 获取问题列表
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20171214
     */
    public function getQuestionAction()
    {
        $parameters['conditions'] = 'bDelete = 0';
        return $this->sendJsonResponse(
            Main::runModelPage('\\Admin\\Models\\ask\\XhaskQuestion', $parameters, $this->questionEnum)
        );
    }

    /**
     * 根据id删除相应题目
     *
     * create by ck 20160722
     * modify by ck 20160924    结构更改
     */
    public function delDataAction()
    {
        $this->view->disable();
        $this->request->isPost() or die;
        UserPower::checkUserPower('Ask_QuestionList_Del') or die('（109105005）无操作权限！');
        $ids = $this->request->getPost('ids');
        XhaskQuestion::deleteRecordById($ids) or die('（109105006）删除失败！');
        echo '删除成功！';
        Main::createCommitLog('ask', 'Question', 'del', array('ids' => $ids), null, '批量删除');
    }

    /**
     * 增加问题及选项
     *
     * create by ck 20160725
     * modify by ck 20160924
     */
    public function addQuestionOptionAction()
    {
        $this->view->disable();
        $this->request->isPost() or die;
        $realData = Main::getRealData($this->request->getPost());
        UserPower::checkUserPower('Ask_QuestionList_Add') or die(Main::showMessageModal('无操作权限！', 109105007));
        $dbRollback = false;
        $this->db->begin();
        $question = XhaskQuestion::createRecord($realData);
        $question->insertData() or die(Main::showMessageModal('数据保存失败！', 109105008));
        $optionContents = $this->request->getPost('option_content');
        if (in_array($question->iQueType, array(1, 2))) {//如果为单选或多选则添加选项
            foreach ($optionContents as $optionIndex => $optionContent) {
                if (!$optionContent) {
                    continue;
                }
                $option = XhaskOption::createRecord($question->iAQId, $optionContent);
                if (!$option->insertData()) {
                    $dbRollback = true;
                    goto dealTrans;
                }
            }
        }
        dealTrans:
        if ($dbRollback) {
            $this->db->rollback();
            die(Main::showMessageModal('数据保存失败！', 109105009));
        }
        Main::createCommitLog('ask', 'Question', 'add', $question, $question->iAQId);
        $this->db->commit();
    }

    /**
     * 选择服务人员页面
     *
     * create by ck 20160726
     * modify by ck 20160924
     */
    public function askChooseServerAction()
    {
        $this->view->pick('ask/askChooseServer');
        Assets::easyUI('js/ask/askChooseServer.js');
        UserPower::checkUserPower('Ask_QuestionList_CreateSurvey')
            or die(Main::showMessageModal('抱歉，您没有查看此页面的权限！', 109105010));
        $this->view->setVar('List', Template::createList('List', 'XHSys_User'));
    }

    /**
     * 问卷信息页面
     *
     * create by ck 20160726
     * modify by ck 20160926
     */
//    public function askSurveyFormAction()
//    {
//        $this->view->pick('ask/askSurveyForm');
//        Assets::datetimePicker('js/ask/askSurveyForm.js');
//        UserPower::checkUserPower('Ask_QuestionList_CreateSurvey') or die(Main::showMessageModal('抱歉，您没有查看此页面的权限！', 109105011));
//        Template::exists('XHAsk_Survey', 'form') or die(Main::showMessageModal('表单模板文件不存在，请先创建！', 109105012));
//        $serverIds   = $this->request->getQuery('sServerIds');
//        $questionIds = $this->request->getQuery('mAQId');
//        $serverIds   or die(Main::showMessageModal('未选中服务人员！', 109105013));
//        $questionIds or die(Main::showMessageModal('未选中题目！', 109105014));
//        $this->view->setVars(array(
//            'Form'          => Template::createForm('XHAsk_Survey'),
//            'serverIds'     => $serverIds,
//            'questionIds'   => $questionIds,
//        ));
//    }

    /**
     * 添加问卷信息
     *
     * create by ck 20160726
     */
//    public function modifySurveyDataAction()
//    {
//        $this->view->disable();
//        $this->request->isPost() or die;
//        UserPower::checkUserPower('Ask_QuestionList_CreateSurvey') or die(Main::showMessageModal('没有操作权限！', 109105015));;
//        $sServerIds = explode(',', $this->request->getPost('XHAsk_Survey,sServerIds'));
//        $dbRollBack = false;
//        $this->db->begin();
//        $realData = Main::getRealData($this->request->getPost());
//        $obj = null;
//        foreach($sServerIds as $serverId){
//            $obj = XhaskSurvey::createRecord($realData, $serverId);
//            if(!$obj->insertData()){
//                $dbRollBack = true;
//                break;
//            }
//        }
//        if($dbRollBack){
//            $this->db->rollback();
//            die(Main::showMessageModal('创建失败！', 109105016));
//        }
//        Main::createCommitLog('ask', 'Survey', 'add',
//            array_merge(array('sServerId' => $this->request->getPost('XHAsk_Survey,sServerIds')), get_object_vars($obj)),
//            null, '批量创建问卷');
//        echo Main::showMessageModal('创建成功！');
//        $this->db->commit();
//    }

    /**
     * 问卷列表页面
     *
     * create by ck 20160726
     * modify by ck 20160926
     * modify by ck 20171212
     */
    public function surveyAction()
    {
        $this->view->setTemplateBefore('listForm');
        Main::showNavPosition();
        Assets::easyUI();
        Assets::select2('js/ask/survey.js');
        if (!UserPower::checkUserPower('Ask_SurveyList')) {
            return $this->sendViewError('无查看权限');
        }
        $listButtonArr = [];
        if (UserPower::checkUserPower('Ask_SurveyList_Add')) {
            $listButtonArr[] = ['id' => 'bt_list_add', 'text' => '新增', 'icon' => 'fa-plus'];
        }
        if (UserPower::checkUserPower('Ask_SurveyList_Del')) {
            $listButtonArr[] = ['id' => 'bt_list_del', 'text' => '删除', 'icon' => 'fa-trash'];
        }
        if (UserPower::checkUserPower('Ask_SurveyList_Edit')) {
            $listButtonArr[] = ['id' => 'bt_list_question', 'text' => '设置题目', 'icon' => 'fa-question'];
            $listButtonArr[] = ['id' => 'bt_list_enable', 'text' => '设置启用', 'icon' => 'fa-chain'];
            $listButtonArr[] = ['id' => 'bt_list_disable', 'text' => '设置禁用', 'icon' => 'fa-chain-broken'];
        }
        $listButtonArr[] = ['id'=>'bt_list_statistics', 'text'=>'查看统计', 'plain'=>'true', 'icon'=>'fa-eye'];
        $this->surveyEnum['sSchoolId']  = XhschoolInfo::getSchoolSupportArray();
        $this->surveyEnum['sUserType'] = [
            '1'   => '学生',
            '4'   => '教师'
        ];
        return $this->view->setVars([
            'List'       => Template::createList('list', 'XHAsk_Survey', [
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr)
            ]),
            'Form'       => Template::createForm('XHAsk_Survey', $this->surveyEnum),
            'FormButton' => Template::createButtonToolBar(Main::createFormButton('Ask_SurveyList'))
        ]);
    }

    /**
     * 根据学校id获取班级列表
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20190123
     */
    public function getSchoolAdClassAction()
    {
        $schoolId = $this->request->getPost('schoolId', 'int');
        if (!$schoolId) {
            return $this->sendErrorResponse(400, '学校id不能为空');
        }
        try {
            $classNames = XhsysUser::find([
                'columns'    => 'sAdClsName',
                'conditions' => 'iUserType = 1 AND bDelete = 0 AND bDisable = 0 AND iSchoolId = :schoolId:',
                'bind'       => ['schoolId' => $schoolId],
                'group'      => 'sAdClsName'
            ])->toArray();
            return $this->sendJsonResponse(array_filter(array_column($classNames, 'sAdClsName')));
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, '系统异常', $e->getMessage());
        }
    }

    /**
     * 获取问卷列表
     *
     * create by ck 20160726
     * modify by ck 20160926
     * modify by ck 20171214    重构
     */
    public function getSurveyAction()
    {
        $parameters = [
            'conditions' => 'bDelete = 0'
        ];
        $data = Main::runModelPage('\\Admin\\Models\\ask\\XhaskSurvey', $parameters, $this->surveyEnum);
        Tool::runTimestamp($data['rows'], ['iStartTime', 'iEndTime']);
        return $this->sendJsonResponse($data);
    }

    /**
     * 保存问卷
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20171212
     */
    public function saveSurveyAction()
    {
        if (!UserPower::checkUserPower('Ask_SurveyList_Add')) {
            return $this->sendErrorResponse(403, '无操作权限');
        }
        try {
            $obj = new XhaskSurvey();
            $obj->assign($this->request->getPost());
            $obj->iStartTime = strtotime($obj->iStartTime) ?: time();
            $obj->iEndTime   = strtotime($obj->iEndTime);
            if (!$obj->save()) {
                throw new \Exception('保存失败：' . $obj->getMessages()[0]);
            }
            return $this->sendSuccessResponse('保存成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 删除问卷
     *
     * create by ck 20160726
     * modify by ck 20160926    结构更改
     * modify by ck 20171214    重构
     */
    public function delSurveyAction()
    {
        $ids = $this->request->getPost('ids', 'int');
        if (!$ids) {
            return $this->sendErrorResponse(400, '缺少id参数');
        }
        if (!UserPower::checkUserPower('Ask_SurveyList_Del')) {
            return $this->sendErrorResponse(403, '无删除权限');
        }
        $result = XhaskSurvey::deleteRecord('iASId', $ids);
        if (!$result) {
            return $this->sendErrorResponse(400, '删除失败');
        }
        return $this->sendSuccessResponse('删除成功');
    }

    /**
     * 设置问卷状态
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20171215
     */
    public function setSurveyStatusAction()
    {
        $ids    = $this->request->getPost('ids', 'int');
        $status = $this->request->getPost('status', 'int');
        if (!$ids) {
            return $this->sendErrorResponse(400, '缺少id参数');
        }
        if (!UserPower::checkUserPower('Ask_SurveyList_Edit')) {
            return $this->sendErrorResponse(403, '无操作权限');
        }
        try {
            $result = $this->modelsManager->executeQuery(
                "update \\Admin\\Models\\ask\\XhaskSurvey set bDisable = :status: where iASId in ({idArr:array})",
                ['status' => $status, 'idArr' => $ids]
            );
            if (!$result) {
                throw new \Exception('操作失败');
            }
            return $this->sendSuccessResponse('操作成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 问卷题目设置页面
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by ck 20171215
     */
    public function surveyQuestionAction()
    {
        $id = $this->request->getQuery('id', 'int');
        if (!$id) {
            return $this->sendViewError('缺少问卷id');
        }
        $obj = XhaskSurvey::findFirst($id);
        if (!$obj) {
            return $this->sendViewError('找不到相应记录');
        }
        if (!$obj->bMutable) {
            return $this->sendViewError('该记录已不可修改');
        }
        $this->view->setTemplateBefore('listForm');
        Assets::easyUI('js/ask/surveyQuestion.js');
        return $this->view->setVars([
            'List'  => Template::createList('list', 'XHAsk_Question'),
        ]);
    }

    /**
     * 设置问卷题目
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface|string
     *
     * create by ck 20171214
     */
    public function setSurveyQuestionAction()
    {
        $id     = $this->request->getPost('id', 'int');
        $queIds = $this->request->getPost('queIds', 'int');
        if (!$id || !$queIds) {
            return $this->sendErrorResponse(400, '缺少参数');
        }
        $obj = XhaskSurvey::findFirst($id);
        if (!$obj) {
            return $this->sendViewError('找不到相应记录');
        }
        if (!$obj->bMutable) {
            return $this->sendViewError('该记录已不可修改');
        }
        $obj->mAQId = implode(',', $queIds);
        if (!$obj->save()) {
            return $this->sendErrorResponse(500, '保存失败');
        }
        return $this->sendSuccessResponse('保存成功');
    }

    /**
     * 设置问卷启用/禁用
     *
     * create by ck 20160726
     */
//    public function setSurveyStateAction()
//    {
//        $this->view->disable();
//        $ids    = $this->request->getPost('ids');
//        $target = $this->request->getPost('target');
//        switch($target){
//            case 'enable':      $sqlParamsStr = "bAskEnable = 1"; break;
//            case 'disable':     $sqlParamsStr = "bAskEnable = 0"; break;
//            default: die('（109105021）无此操作类型');
//        }
//        $sqlStr = "UPDATE \\Admin\\Models\\ask\\XhaskSurvey SET $sqlParamsStr WHERE iASId IN ($ids)";
//        $query = $this->modelsManager->executeQuery($sqlStr);
//        $query or die('（109105022）操作失败！');
//        echo '操作成功！';
//        Main::createCommitLog('ask', 'Survey', $target, array('ids'=>$ids, 'type'=>$target), null, '批量启用/禁用');
//    }

    /**
     * 统计页面
     * 将题目，选项，答案组合到一个数组中，经过组合再显示到页面
     *
     * create by ck 20160801
     */
    public function askSurveyStatisticsAction()
    {
        $this->view->pick('ask/askSurveyStatistics');
        $this->assets->addCss('assets/jquery/jquery.webui-popover.css');
        $this->assets->addJs('assets/jquery/jquery.webui-popover.js');
        Assets::importJs('js/ask/askSurveyStatistics.js');
        $surveyId  = $this->request->getQuery('iASId');
        try {
            $survey = XhaskSurvey::findFirst($surveyId);
            if (!trim($survey->mAQId, ',')) {
                return $this->sendViewError('该问卷下无题目');
            }
            $questions = XhaskQuestion::getQuestionById(trim($survey->mAQId, ','));
            $questionIds = array_column($questions, 'iAQId');
            $newQuestions = array();
            foreach ($questions as $question) {
                $newQuestions[$question['iAQId']] = $question;
            }
            //添加每题选项信息
            $options = XhaskOption::getOptionsByQueIdArr($questionIds);
            foreach ($options as $option) {
                $newQuestions[$option['iAQId']]['options'][$option['iAOId']] = $option;
            }
            //添加每题回答人数信息
            $questionAnswerNum = XhaskAnswer::getAnswerNumBySurveyId($surveyId);
            foreach ($questionAnswerNum as $answerNum) {
                $newQuestions[$answerNum['iAQId']]['iAnswerNum'] = $answerNum['iAnswerNum'];
            }
            //添加每个选项回答人数及详情
            $optionAnswerNum = XhaskAnswer::getAnswerDetailBySurveyId($surveyId);
            foreach ($optionAnswerNum as $optionNum) {
                switch ($newQuestions[$optionNum['iAQId']]['iQueType']) {
                    //选择题则在选项中添加该选项选择数量
                    case 1:
                    case 2:
                        $newQuestions[$optionNum['iAQId']]['options'][$optionNum['iAOId']]['iAnswerNum'] = $optionNum['iAnswerNum'];
                        $newQuestions[$optionNum['iAQId']]['options'][$optionNum['iAOId']]['iUserId']    = $optionNum['iUserId'];
                        break;
                    //文本题则将答案及回答该答案的人数填充进去
                    case 4:
                    case 5:
                        $newQuestions[$optionNum['iAQId']]['answers'][] = array(
                            'mAnswer' => $optionNum['mAnswer'],
                            'iAnswerNum' => $optionNum['iAnswerNum'],
                            'signAAId' => $optionNum['iAAId'],
                            'iUserId' => $optionNum['iUserId']
                        );
                        break;
                }
            }
            $newQuestions = array_values($newQuestions);
            foreach ($newQuestions as $key => $newQuestion) {
                if (isset($newQuestion['options']))
                    $newQuestions[$key]['options'] = array_values($newQuestion['options']);
            }
            $newQuestionsStr = self::runSurveyQuestion($newQuestions, $surveyId);
            return $this->view->setVars(array(
                'questionsStr' => $newQuestionsStr,
                'surveyInfo' => $survey
            ));
        } catch (\Exception $e) {
            return $this->sendViewError($e->getMessage());
        }
    }

    /**
     * 根据列表生成相应html代码
     *
     * @param $questions
     * @param $surveyId
     * @return string
     *
     * create by ck 20160802
     * modify by ck 20160913    防止内存泄露
     */
    public static function runSurveyQuestion($questions, $surveyId)
    {
        require_once(APP_PATH . '/helpers/simple_html_dom.php');
        $questionListStr = '';
        $num = 1;
        foreach ($questions as $question) {
            $questionStr = str_get_html(
                '<div class="survey-question">
                    <p><span></span><i></i></p>
                    <table class="table table-hover">
                        <thead>
                            <tr>
                                <th></th>
                                <th></th>
                                <th></th>
                            </tr>
                        </thead>
                        <tbody>

                        </tbody>
                    </table>
                </div>'
            );
            $questionStr->find('div', 0)->aqid = $question['iAQId'];
            $questionStr->find('p i', 0)->innertext = '(' . (isset($question['iAnswerNum']) ? $question['iAnswerNum'] : 0) .'条有效填写)';
            switch ($question['iQueType']) {
                case 1:
                    $questionStr->find('p span', 0)->innertext = '单选题';
                    $questionStr->find('table thead tr th', 0)->innertext = '选项';
                    $questionStr->find('table thead tr th', 1)->innertext = '选择人数';
                    break;
                case 2:
                    $questionStr->find('p span', 0)->innertext = '多选题';
                    $questionStr->find('table thead tr th', 0)->innertext = '选项';
                    $questionStr->find('table thead tr th', 1)->innertext = '选择人数';
                    break;
                case 4:
                    $questionStr->find('p span', 0)->innertext = '单行文本框';
                    $questionStr->find('table thead tr th', 0)->innertext = '文本答案';
                    $questionStr->find('table thead tr th', 1)->innertext = '人数';
                    break;
                case 5:
                    $questionStr->find('p span', 0)->innertext = '多行文本框';
                    $questionStr->find('table thead tr th', 0)->innertext = '文本答案';
                    $questionStr->find('table thead tr th', 1)->innertext = '人数';
                    break;
            }
            if (isset($question['options'])) {            //选择题
                foreach ($question['options'] as $option) {
                    $html = "<tr><td>{$option['sOptionContent']}</td>";
                    if (isset($option['iAnswerNum'])) {
                        if ($option['iAnswerNum'] == 1) {
                            $userInfo = [['userId' => $option['iUserId']]];
                            Main::runUserName($userInfo, ['userId' => 'userName']);
                            Main::runUserSchoolId($userInfo, 'userId', 'schoolId');
                            Main::runSchoolNameByIdStr($userInfo, ['schoolId' => 'schoolName'], true);
                            $userInfo = $userInfo[0];
                            $html .= "<td>{$option['iAnswerNum']}</td><td>{$userInfo['userName']} {$userInfo['schoolName']}</td>";
                        } else {
                            $html .= "<td>{$option['iAnswerNum']}</td><td><a qtype='option' qinfo='{$surveyId}_{$question['iAQId']}_{$option['iAOId']}'>查看人员</a></td>";
                        }
                    } else {
                        $html .= '<td>0</td><td>查看人员</td>';
                    }
                    $html .= '</tr>';
                    $questionStr->find('table tbody', 0)->innertext .= $html;
//                    $questionStr->find('table tbody', 0)->innertext .= "<tr>"
//                        . "<td>{$option['sOptionContent']}</td>"
//                        . (isset($option['iAnswerNum'])
//                            ? "<td>{$option['iAnswerNum']}</td><td><a qtype='option' qinfo='{$surveyId}_{$question['iAQId']}_{$option['iAOId']}'>查看人员</a></td>"
//                            : "<td>0</td><td>查看人员</td>")
//                        . "</tr>";
                }
            } elseif (isset($question['answers'])) {        //文本题
                foreach ($question['answers'] as $answer) {
                    $html = "<tr><td>{$answer['mAnswer']}</td>";
                    if (isset($answer['iAnswerNum'])) {
                        if ($answer['iAnswerNum'] == 1) {
                            $userInfo = [['userId' => $answer['iUserId']]];
                            Main::runUserName($userInfo, ['userId' => 'userName']);
                            Main::runUserSchoolId($userInfo, 'userId', 'schoolId');
                            Main::runSchoolNameByIdStr($userInfo, ['schoolId' => 'schoolName'], true);
                            $userInfo = $userInfo[0];
                            $html .= "<td>{$answer['iAnswerNum']}</td><td>{$userInfo['userName']} {$userInfo['schoolName']}</td>";
                        } else {
                            $html .= "<td>{$answer['iAnswerNum']}</td><td><a qtype='answer' qinfo='{$surveyId}_{$question['iAQId']}_{$answer['signAAId']}'>查看人员</a></td>";
                        }
                    } else {
                        $html .= '<td>0</td><td>查看人员</td>';
                    }
                    $html .= '</tr>';
                    $questionStr->find('table tbody', 0)->innertext .= $html;
//                    $questionStr->find('table tbody', 0)->innertext .= "<tr>"
//                        . "<td>{$answer['mAnswer']}</td>"
//                        . "<td>{$answer['iAnswerNum']}</td>"
//                        . "<td><a qtype='answer' qinfo='{$surveyId}_{$question['iAQId']}_{$answer['signAAId']}'>查看人员</a></td>"
//                        . "</tr>";
                }
            }
            //防止span标签读取不到，p节点后于span操作
            $questionStr->find('p', 0)->innertext = $num . '. ' . $question['sQueTitle'] . $questionStr->find('p', 0)->innertext;
            $questionListStr .= $questionStr->outertext;
            $questionStr->clear();
            unset($questionStr);
            $num++;
        }
        $questionListStr = '<div class="survey-questions">' . $questionListStr . '</div>';
        return $questionListStr;
    }

    /**
     * 用户信息展示页面
     * 根据问卷ID，问题ID，选项ID/答案ID找出相应用户的姓名及学校信息
     *
     * create by ck 20160803
     * modify by ck 20180130    根据时间排序
     */
    public function askSurveyOptionPeopleAction()
    {
        $this->view->disable();
        $this->request->isPost() or die;
        $type = $this->request->getPost('type');
        $info = explode('_', $this->request->getPost('info'));
        $surveyId   = $info[0];
        $questionId = $info[1];
        if ($type == 'option') {
            //查询选择该选项的用户ID
            $userInfo = XhaskAnswer::find(array(
                'columns' => 'iUserId',
                'conditions' => 'iASId = :iASId: AND iAQId = :iAQId: AND iAOId = :iAOId:',
                'bind' => array(
                    'iASId' => $surveyId,
                    'iAQId' => $questionId,
                    'iAOId' => $info[2],
                ),
                'order' => 'iAAId desc'
            ))->toArray();
        } else {
            //查询选中改答案ID的文本内容
            $answerText = XhaskAnswer::findFirst($info[2])->mAnswer;
            //查询该问卷下文本内容相同的答案
            $userInfo = XhaskAnswer::find(array(
                'columns'       => 'iUserId',
                'conditions'    => 'iASId = :iASId: AND iAQId = :iAQId: AND mAnswer = :mAnswer:',
                'bind'          => array(
                    'iASId'         => $surveyId,
                    'iAQId'         => $questionId,
                    'mAnswer'       => $answerText,
                ),
                'order'         => 'iAAId desc'
            ))->toArray();
        }
        Main::runUserName($userInfo, ['iUserId' => 'sUserName']);
        Main::runUserSchoolId($userInfo, 'iUserId', 'iSchoolId');
        Main::runSchoolNameByIdStr($userInfo, ['iSchoolId' => 'sSchoolName'], true);
//        $userIdArr = array_column($userIdArr ,'iUserId');
//        //查询选中该选项的用户姓名及学校名称
//        $userInfo = $this->modelsManager->createBuilder()
//            ->columns('XhsysUser.sUserName,C.sSchoolName')
//            ->from(['XhsysUser' => 'Admin\Models\user\XhsysUser'])
//            ->leftJoin('Admin\Models\school\XhschoolInfo', 'XhsysUser.iSchoolId = C.iSchoolId', 'C')
//            ->inWhere('XhsysUser.iUserId', $userIdArr)
//            ->getQuery()
//            ->execute()
//            ->toArray();
        $tableHtml  = '<table class="table table-hover table-condensed">';
        $tableHtml .= '<thead><tr><th>姓名</th><th>学校</th></tr></thead>';
        $tableHtml .= '<tbody>';
        foreach ($userInfo as $user) {
            $tableHtml .= '<tr>';
            $tableHtml .= '<td>' . $user['sUserName'] . '</td>';
            $tableHtml .= '<td>' . $user['sSchoolName'] . '</td>';
            $tableHtml .= '</tr>';
        }
        $tableHtml .= '</tbody>';
        $tableHtml .= '</table>';
        echo $tableHtml;
    }

    /**
     * 根据类型导出问卷
     *
     * @return string
     *
     * create by ck 20181023
     */
    public function exportSurveyStatsAction()
    {
        $surveyId = $this->request->getQuery('surveyId', 'int');
        $type = $this->request->getQuery('type', 'int');
        if (!$surveyId) {
            return $this->sendViewError('缺少问卷id参数，无法导出');
        }
        try {
            switch ($type) {
                case 1:
                    return $this->exportSurvey1($surveyId);
                    break;
                case 2:
                    return $this->exportSurvey2($surveyId);
                    break;
                default:
                    throw new \Exception('导出类型错误');
            }
        } catch (\Exception $e) {
            return $this->sendViewError($e->getMessage());
        }
    }

    /**
     * 问卷统计导出为excel
     *
     * @param $surveyId
     * @return string
     *
     * create by ck 20180201
     * modify by ck 20180906    重构
     * modify by ck 20190123    添加班级信息
     */
    private function exportSurvey1($surveyId)
    {
        $surveyInfo = $this->getSurveyStatsInfo($surveyId, true);
        $fileName   = $surveyInfo['title'] . '-模板1.xlsx';

        $objPHPExcel = new Spreadsheet();
        $objPHPExcel->setActiveSheetIndex(0);

        foreach ($surveyInfo['questions'] as $index => $question) {
            $rowIndex = 3;
            if ($index > 0) {
                $objPHPExcel->createSheet();
            }
            $sheet = $objPHPExcel->getSheet($index);
            $sheet->setTitle('问题' . ++$index);
            $sheet->setCellValue('A1', $question['sQueTitle']);
            if (isset($question['options'])) {
                foreach ($question['options'] as $option) {
                    $sheet->setCellValue('A' . $rowIndex, '选项：');
                    $sheet->setCellValue('B' . $rowIndex, $option['sOptionContent']);
                    $rowIndex++;
                    if (!isset($option['users'])) {
                        $rowIndex++;
                        continue;
                    }
                    $sheet->setCellValue('A' . $rowIndex, '人员：');
                    foreach ($option['users'] as $user) {
                        $sheet->setCellValue('B' . $rowIndex, $user['userName']);
                        $sheet->setCellValue('C' . $rowIndex, $user['schoolName']);
                        $sheet->setCellValue('D' . $rowIndex, $user['className']);
                        $rowIndex++;
                    }
                    $rowIndex++;
                }
            } elseif (isset($question['answers'])) {
                foreach ($question['answers'] as $answer) {
                    $sheet->setCellValue('A' . $rowIndex, '答案：');
                    $sheet->setCellValue('B' . $rowIndex, $answer['mAnswer']);
                    $rowIndex++;
                    if (!isset($answer['users'])) {
                        $rowIndex++;
                        continue;
                    }
                    $sheet->setCellValue('A' . $rowIndex, '人员：');
                    foreach ($answer['users'] as $user) {
                        $sheet->setCellValue('B' . $rowIndex, $user['userName']);
                        $sheet->setCellValue('C' . $rowIndex, $user['schoolName']);
                        $sheet->setCellValue('D' . $rowIndex, $user['className']);
                        $rowIndex++;
                    }
                    $rowIndex++;
                }
            }
        }

        //导出代码
        $this->view->disable();
        $objWriter = new Xlsx($objPHPExcel);
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="' . $fileName . '"');
        header('Cache-Control: max-age=0');
        $objWriter->save('php://output');
        return true;
    }

    /**
     * 导出问卷-模板2
     *
     * @param $surveyId
     * @return bool
     * @throws \Exception
     *
     * create by ck 20181023
     * modify by ck 20190123    添加班级信息
     */
    private function exportSurvey2($surveyId)
    {
        $surveyInfo = $this->getSurveyInfo($surveyId);
        $questions  = &$surveyInfo['questions'];

        //获取问卷下用户信息
        $users = XhaskAnswer::find([
            'columns' => 'DISTINCT(iUserId) AS userId',
            'conditions' => 'iASId = :surveyId:',
            'bind' => ['surveyId' => $surveyId]
        ])->toArray();
        if (!$users) {
            throw new \Exception('该问卷暂无用户回答');
        }
        Main::runUserName($users, ['userId' => 'userName']);
        Main::runUserSchoolId($users, 'userId', 'schoolId');
        Main::runUserClassName($users, 'userId', 'className');
        School::runName($users, ['schoolId' => 'schoolName']);

        //处理excel标题
        $excelTitle = ['姓名', '学校', '班级'];
        $index = 1;
        foreach ($questions as $queId => $que) {
            $excelTitle[] = $index++ . '.' . $que['sQueTitle'];
        }

        //循环用户答题情况
        $excelData = [];
        foreach ($users as $user) {
            $userId = $user['userId'];
            $answers = XhaskAnswer::find([
                'columns' => 'iAQId,iAOId,mAnswer',
                'conditions' => 'iASId = :surveyId: AND iUserId = :userId:',
                'bind' => ['surveyId' => $surveyId, 'userId' => $userId]
            ])->toArray();

            $row = [$user['userName'], $user['schoolName'], $user['className']];
            foreach ($questions as $queId => $que) {
                $val = [];
                foreach ($answers as $answer) {
                    if ($answer['iAQId'] != $queId) {
                        continue;
                    }
                    switch ($que['iQueType']) {
                        case 1:
                            $val[] = $que['options'][$answer['iAOId']]['sOptionContent'];
                            break 2;
                        case 2:
                            $val[] = $que['options'][$answer['iAOId']]['sOptionContent'];
                            continue 2;
                        case 4:
                        case 5:
                            $val[] = $answer['mAnswer'];
                            break 2;
                    }
                }
                $row[] = implode(',', $val);
            }
            $excelData[] = $row;
        }

        //导出
        $this->view->disable();
        $fileName = $surveyInfo['title'] . '-模板2';
        Tool::exportExcelOnline($fileName, $excelTitle, $excelData);
        return true;
    }

    /**
     * 组合问卷信息
     *
     * @param $surveyId
     * @return array
     * @throws \Exception
     *
     * create by ck 20181023
     */
    private function getSurveyInfo($surveyId)
    {
        $survey = XhaskSurvey::findFirst($surveyId);
        if (!$survey) {
            throw new \Exception('无问卷信息');
        }
        $questionIds = explode(',', trim($survey->mAQId, ','));
        if (!$questionIds) {
            throw new \Exception('该问卷下无题目信息');
        }
        $questions = XhaskQuestion::find([
            'columns'    => 'iAQId,sQueTitle,sQueExplain,iQueType,iChooseNum,bRequire',
            'conditions' => 'bDelete = 0 AND iAQId IN ({queIds:array})',
            'bind'       => ['queIds' => $questionIds]
        ])->toArray();
        $questions = array_column($questions, null, 'iAQId');
        //添加每题选项信息
        $options =  XhaskOption::find([
            'columns'    => 'iAOId,iAQId,sOptionContent',
            'conditions' => 'bDelete = 0 AND iAQId IN ({queIds:array})',
            'bind'       => ['queIds' => $questionIds]
        ])->toArray();
        foreach ($options as $option) {
            $questions[$option['iAQId']]['options'][$option['iAOId']] = $option;
        }
        return [
            'title'     => $survey->sTitle,
            'explain'   => $survey->mExplain,
            'questions' => $questions
        ];
    }

    /**
     * 获取问卷统计信息
     *
     * @param $surveyId
     * @param bool|false $getUsers
     * @return array
     * @throws \Exception
     *
     * create by ck 20180131
     * modify by ck 20181023
     * modify by ck 20190123    添加班级信息
     */
    private function getSurveyStatsInfo($surveyId, $getUsers = false)
    {
//        $survey = XhaskSurvey::findFirst($surveyId);
//        if (!$survey) {
//            throw new \Exception('无问卷信息');
//        }
//        $questionIds = explode(',', trim($survey->mAQId, ','));
//        if (!$questionIds) {
//            throw new \Exception('该问卷下无题目信息');
//        }
//        $questions = XhaskQuestion::find([
//            'columns'    => 'iAQId,sQueTitle,sQueExplain,iQueType,iChooseNum,bRequire',
//            'conditions' => 'bDelete = 0 AND iAQId IN ({queIds:array})',
//            'bind'       => ['queIds' => $questionIds]
//        ])->toArray();
//        $questions = array_column($questions, null, 'iAQId');
//        //添加每题选项信息
//        $options =  XhaskOption::find([
//            'columns'    => 'iAOId,iAQId,sOptionContent',
//            'conditions' => 'bDelete = 0 AND iAQId IN ({queIds:array})',
//            'bind'       => ['queIds' => $questionIds]
//        ])->toArray();
//        foreach ($options as $option) {
//            $questions[$option['iAQId']]['options'][$option['iAOId']] = $option;
//        }
        $surveyInfo = $this->getSurveyInfo($surveyId);
        $questions = $surveyInfo['questions'];
        //添加每题回答人数信息
        $questionAnswerNum = XhaskAnswer::find([
            'columns'       => 'iAQId,count(DISTINCT(iUserId)) as iAnswerNum',
            'conditions'    => 'iASId = :surveyId:',
            'group'         => 'iAQId',
            'bind'          => ['surveyId' => $surveyId]
        ])->toArray();
        foreach ($questionAnswerNum as $answerNum) {
            $questions[$answerNum['iAQId']]['iAnswerNum'] = $answerNum['iAnswerNum'];
        }
        //添加每个选项回答人数及详情
        $optionAnswerNum = XhaskAnswer::find([
            'columns'       => 'iAAId,iAQId,iAOId,mAnswer,count(DISTINCT(iUserId)) AS iAnswerNum,iUserId',
            'conditions'    => 'iASId = :surveyId:',
            'group'         => 'iAQId,iAOId,mAnswer',
            'bind'          => ['surveyId' => $surveyId]
        ])->toArray();
        //填充用户列表
        $userIds = $answerUsers = [];
        if ($getUsers) {
            $answers = XhaskAnswer::find([
                'columns'    => 'iAAId,iAQId,iAOId,mAnswer,iUserId',
                'conditions' => 'iASId = :surveyId:',
                'bind'       => ['surveyId' => $surveyId]
            ])->toArray();
            foreach ($answers as $answer) {
                switch ($questions[$answer['iAQId']]['iQueType']) {
                    case 1:
                    case 2:
                        $answerUsers[$answer['iAQId']][$answer['iAOId']][] = $answer['iUserId'];
                        $userIds[] = $answer['iUserId'];
                        break;
                    case 4:
                    case 5:
                        $answerUsers[$answer['iAQId']][$answer['mAnswer']][] = $answer['iUserId'];
                        $userIds[] = $answer['iUserId'];
                        break;
                }
            }
        }
        foreach ($optionAnswerNum as $optionNum) {
            switch ($questions[$optionNum['iAQId']]['iQueType']) {
                //选择题则在选项中添加该选项选择数量
                case 1:
                case 2:
                    $option = [
                        'iAnswerNum' => $optionNum['iAnswerNum']
                    ];
                    if ($optionNum['iAnswerNum'] == 1) {
                        $option['userId'] = $optionNum['iUserId'];
                        $userIds[] = $optionNum['iUserId'];
                    }
                    $questions[$optionNum['iAQId']]['options'][$optionNum['iAOId']] += $option;
                    break;
                //文本题则将答案及回答该答案的人数填充进去
                case 4:
                case 5:
                    $answer = [
                        'mAnswer'    => $optionNum['mAnswer'],
                        'iAnswerNum' => $optionNum['iAnswerNum'],
                        'signAAId'   => $optionNum['iAAId']
                    ];
                    if ($optionNum['iAnswerNum'] == 1) {
                        $answer['userId'] = $optionNum['iUserId'];
                        $userIds[] = $optionNum['iUserId'];
                    }
                    $questions[$optionNum['iAQId']]['answers'][$optionNum['mAnswer']] = $answer;
                    break;
            }
        }
        //处理单用户姓名学校
        $userIds  = array_unique($userIds);
        $userInfo = [];
        foreach ($userIds as $userId) {
            $userInfo[$userId] = ['userId' => $userId];
        }
        Main::runUserName($userInfo, ['userId' => 'userName']);
        Main::runUserSchoolId($userInfo, 'userId', 'schoolId');
        Main::runUserClassName($userInfo, 'userId', 'className');
        Main::runSchoolNameByIdStr($userInfo, ['schoolId' => 'schoolName'], true);
        $questions = array_values($questions);
        foreach ($questions as &$question) {
            if (isset($question['options'])) {
                foreach ($question['options'] as &$option) {
                    if (isset($option['userId'])) {
                        $option += $userInfo[$option['userId']];
                    }
                    if ($getUsers) {
                        if (isset($answerUsers[$question['iAQId']][$option['iAOId']])) {
                            foreach ($answerUsers[$question['iAQId']][$option['iAOId']] as $userId) {
                                $option['users'][] = $userInfo[$userId];
                            }
                        }
                    }
                }
                $question['options'] = array_values($question['options']);
            }
            if (isset($question['answers'])) {
                foreach ($question['answers'] as &$answer) {
                    if (isset($answer['userId'])) {
                        $answer += $userInfo[$answer['userId']];
                    }
                    if ($getUsers) {
                        foreach ($answerUsers[$question['iAQId']][$answer['mAnswer']] as $userId) {
                            $answer['users'][] = $userInfo[$userId];
                        }
                    }
                }
                $question['answers'] = array_values($question['answers']);
            }
        }
        $surveyInfo['questions'] = $questions;
        return $surveyInfo;
//        return [
//            'title'     => $surveyInfo->sTitle,
//            'explain'   => $survey->mExplain,
//            'questions' => $questions
//        ];
    }

}

